package org.example.httpserver.websocket;

import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.util.concurrent.CopyOnWriteArraySet;

/*
 * @ServerEndPoint注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端
 * 注解的值将被用于监听用户连接的终端访问URL地址，客户端可以通过这个URL来连接到websocket服务器端*/
@ServerEndpoint("/testWebSocket")
@Component
public class WebSocketServer implements WebSocketHandler {
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    //存放每个客户端对应的WebSocket对象
    private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    private WebSocketSession mSession; //当前的连接绘画

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("websocket connected");
        log.info("session id: {}", session.getId());
        this.mSession = session;
        webSocketSet.add(this);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        for (WebSocketServer item : webSocketSet) {
            if(item.mSession.isOpen()){
                item.mSession.sendMessage(new TextMessage("我听到了你的消息"+message.getPayload()));
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("websocket连接异常,session id: {}", session.getId());
        log.error(exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.info("websocket 连接关闭,session id: {}", session.getId());
        webSocketSet.remove(this);
    }

    //是否支持部分消息，也就是消息一段一段发送
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
